#!/bin/sh

# 使用说明，用来提示输入参数
usage() {
    echo "Usage: sh 执行脚本.sh [port|base|modules|stop|rm|rmmodule|sentinel]"
    echo "rmmodule 参数示例: sh 执行脚本.sh rmmodule cloud-mysql"
    exit 1
}

# 开启所需端口
port(){
    firewall-cmd --add-port=80/tcp --permanent
    firewall-cmd --add-port=8080/tcp --permanent
    firewall-cmd --add-port=8848/tcp --permanent
    firewall-cmd --add-port=9848/tcp --permanent
    firewall-cmd --add-port=9849/tcp --permanent
    firewall-cmd --add-port=6379/tcp --permanent
    firewall-cmd --add-port=3306/tcp --permanent
    firewall-cmd --add-port=9100/tcp --permanent
    firewall-cmd --add-port=9200/tcp --permanent
    firewall-cmd --add-port=9201/tcp --permanent
    firewall-cmd --add-port=9202/tcp --permanent
    firewall-cmd --add-port=9203/tcp --permanent
    firewall-cmd --add-port=9300/tcp --permanent
    firewall-cmd --add-port=8718/tcp --permanent
    service firewalld restart
}

# 启动基础环境（必须）
base(){
    docker-compose up -d cloud-mysql cloud-redis cloud-nacos
}
# 消息中间件
xiaoxi(){
#    docker-compose up -d cloud-zookeeper cloud-kafka  cloud-kafka-map
    for service in cloud-zookeeper cloud-kafka  cloud-kafka-map; do
            clean_and_rebuild $service
    done
}

# 启动程序模块（必须）
modules(){
#    docker-compose up -d cloud-nginx cloud-gateway cloud-auth cloud-modules-system
    for service in cloud-nginx cloud-gateway cloud-auth cloud-modules-system cloud-modules-ceshi cloud-modules-file cloud-visual-monitor; do
            clean_and_rebuild $service
    done
}
# 清理并重建容器
clean_and_rebuild() {
    service_name=$1
    # 检查容器是否存在
    if [ "$(docker ps -aq -f name=$service_name)" ]; then
        echo "发现已存在的 $service_name 容器，正在删除..."
        docker stop $service_name
        docker rm -f $service_name
        # 删除关联镜像
        # 检查并删除旧的Docker镜像
        echo "Checking for existing Docker images..."
        EXISTING_IMAGE=$(docker images -q $service_name)
        if [ ! -z "$EXISTING_IMAGE" ]; then
            echo "Removing existing Docker image: $EXISTING_IMAGE"
            if ! docker rmi -f $EXISTING_IMAGE; then
                echo "Failed to remove existing Docker image. Continuing."
            fi
        fi
    fi
    # 重新构建并启动
    docker-compose up -d  $service_name
}
# 启动Sentinel模块
sentinel(){
    docker-compose up -d cloud-sentinel
}

# 关闭所有环境/模块
stop(){
    docker-compose stop
}

# 删除所有环境/模块
rm(){
    docker-compose down
}

# 删除指定模块
update(){
    if [ -z "$2" ]; then
        echo "请指定要删除的模块名称"
        usage
    else
        echo "正在删除模块: $2"
        clean_and_rebuild "$2"
    fi
}

# 根据输入参数，选择执行对应方法
case "$1" in
"port")
    port
;;
"base")
    base
;;
"xiaoxi")
    xiaoxi
;;
"modules")
    modules
;;
"stop")
    stop
;;
"rm")
    rm
;;
"update")
    update "$@"
;;
"sentinel")
    sentinel
;;
*)
    usage
;;
esac